昨天和大家分享了此次實作主題的整體架構,今天要來和大家講解後端抓取 API 並且處理其資料的部分,那話不多說,我們開始!
# src/functions/data.py
import requests as re
def getWeatherData(city) :
targetUrl = f'https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=自己的帳號授權&limit=100&locationName={city}&elementName=Wx,PoP,MinT,MaxT'
result = re.get(targetUrl).json()
return result
# src/functions/process.py
def extractWeatherData(json):
element = json['records']['location'][0]['weatherElement']
wx = []
pop = []
mint = []
maxt = []
for i in range(len(element)):
if i == 0:
wx.append(element[0])
elif i == 1:
pop.append(element[1])
elif i == 2:
mint.append(element[2])
elif i == 3:
maxt.append(element[3])
return wx, pop, mint, maxt
def splitWeatherData(json):
weatherElementLen = len(json)
weatherslotLen = len(json[0][0]['time'])
wx = []
pop = []
mint = []
maxt = []
for i in range(weatherElementLen):
for j in range(weatherslotLen):
if i == 0:
wx.append(json[i][0]['time'][j]['parameter']['parameterName'])
elif i == 1:
pop.append(json[i][0]['time'][j]['parameter']['parameterName'])
elif i == 2:
mint.append(json[i][0]['time'][j]['parameter']['parameterName'])
elif i == 3:
maxt.append(json[i][0]['time'][j]['parameter']['parameterName'])
return wx, pop, mint, maxt
def extractWeatherTime(json):
time = json['records']['location'][0]['weatherElement'][0]['time']
startTime = []
endTime = []
for i in range(len(time)):
startTime.append(time[i]['startTime'])
endTime.append(time[i]['endTime'])
return startTime, endTime
def splitWeatherTime(json):
timePeriod = []
for i in range(3):
startTimeSplit = json[0][i].split(' ')
startTimeDate = startTimeSplit[0].split('-')[1] + '/' + startTimeSplit[0].split('-')[2]
startTimePeriod = startTimeSplit[1].split(':')[0] + ':' + startTimeSplit[1].split(':')[1]
startTime = startTimeDate + ' ' + startTimePeriod
endTimeSplit = json[1][i].split(' ')
endTimeDate = endTimeSplit[0].split('-')[1] + '/' + endTimeSplit[0].split('-')[2]
endTimePeriod = endTimeSplit[1].split(':')[0] + ':' + endTimeSplit[1].split(':')[1]
endTime = endTimeDate + ' ' + endTimePeriod
timePeriod.append(startTime + ' - ' + endTime)
return timePeriod
src/functions/data.py
和資料處理 src/functions/process.py
這兩個,主要是為了之後單元測試的方便。src/functions/process.py
中,我們主要把資料分成兩種類型做處理,分別是「weather time 天氣時間」和「weather data 天氣資訊」,因為他在回傳的資料中分屬於不同的區塊,因此做此判斷處理。